<template>
  <div class="post-question-container">
    <el-card shadow="hover">
      <h2>发布问题</h2>
      <el-form :model="form" label-width="80px" ref="postForm">
        <el-form-item label="标题" :required="true">
          <el-input v-model="form.title" placeholder="简洁描述你的问题"></el-input>
        </el-form-item>

        <el-form-item label="分类">
          <el-select v-model="form.category" placeholder="选择分类">
            <el-option label="学业" value="学业" />
            <el-option label="情感" value="情感" />
            <el-option label="生活" value="生活" />
            <el-option label="心理健康" value="心理健康" />
          </el-select>
        </el-form-item>

        <el-form-item label="详情" :required="true">
          <el-input
              type="textarea"
              v-model="form.content"
              rows="8"
              placeholder="详细描述你的情况，越具体越容易获得有效回复"
          />
        </el-form-item>

        <el-form-item>
          <el-button @click="onCancel">取消</el-button>
          <el-button type="primary" @click="onSubmit">发布</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const router = useRouter()
const form = reactive({
  title: '',
  category: '',
  content: ''
})

const validate = () => {
  if (!form.title.trim()) {
    ElMessage.warning('请输入标题')
    return false
  }
  if (!form.content.trim()) {
    ElMessage.warning('请输入问题详情')
    return false
  }
  return true
}

const onSubmit = async () => {
  if (!validate()) return
  try {
    const res = await axios.post('/api/questions', {
      title: form.title,
      category: form.category,
      content: form.content
    })
    ElMessage.success('问题发布成功')
    // 如果后端返回新问题ID，跳转到详情页；否则回到列表
    const newId = res?.data?.id
    if (newId) {
      router.push({ name: 'QuestionDetail', params: { id: newId } })
    } else {
      router.push({ name: 'QuestionList' })
    }
  } catch (err) {
    console.error(err)
    ElMessage.error('发布失败，请重试')
  }
}

const onCancel = () => {
  router.back()
}
</script>

<style scoped>
.post-question-container {
  max-width: 900px;
  margin: 20px auto;
  padding: 10px;
}
</style>